using Services;
using Services.ObjectPools;
using TMPro;
using UnityEngine;

namespace Gobang
{
    public class ChessNumberDrawer : MonoBehaviour
    {
        private IObjectManager objectManager;
        private ChessboardMono chessboard;

        private void AfterChessChange()
        {
            ObjectPoolUtility.RecycleMyObjects(gameObject);

            int count = chessboard.Chessboard.history.Count;
            bool black = chessboard.Chessboard.history.Count % 2 == 0;
            foreach (Vector2Int position in chessboard.Chessboard.history)
            {
                IMyObject obj = objectManager.Activate("ChessNumber", chessboard.ChessboardToWorld(position), Vector3.zero, transform);
                TextMeshProUGUI tmp = obj.Transform.GetComponent<TextMeshProUGUI>();
                tmp.text = count.ToString();
                tmp.color = count == chessboard.Chessboard.history.Count ? Color.red : (black ? Color.black : Color.white);
                count--;
                black = !black;
            }
        }

        private void Awake()
        {
            objectManager = ServiceLocator.Get<IObjectManager>();
            chessboard = ChessboardMono.FindInstance();
        }

        private void OnEnable()
        {
            chessboard.AfterChessChange += AfterChessChange;
        }

        private void OnDisable()
        {
            chessboard.AfterChessChange -= AfterChessChange;
        }
    }
}